<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="500px"
    top="20vh !important"
    :close-on-click-modal="false"
  >
    <u-form
      ref="uFormRef"
      label-width='160px'
      v-model="form"
      :formArray="formArray"
      :defaultForm="defaultForm"
      @submit="onsubmit"
      @close="visible = false"
      mode="form"
      v-loading="loading"
    />
  </el-dialog>
</template>

<script>
import UForm from "@/components/uForm/index";
import {saveAs} from 'file-saver'
import {
  reqRemoteShutdown,
  reqRemoteRestart,
  reqRemoteSelfCheck,
  reqGetLogMessageCode, reqGetLogFile
} from "@/api/operationAndMonitoring/deviceMonitoring";

const COMMAND_TYPE_DICT = {
  pullLog: {title: '拉取日志', fnName: 'getLogFileMessageCode', key: 'pullLog'},
  restart: {title: '设置重启', fnName: 'restart', key: 'restart'},
  shutdown: {title: '设置关机', fnName: 'shutdown', key: 'shutdown'},
  selfCheck: {title: '设置客户端自检', fnName: 'selfCheck', key: 'selfCheck'},
}

export default {
  name: "RemoteCommandDialog",
  components: {
    UForm
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    // 指令类型 pullLog 或 restart 或 shutdown 或 selfCheck
    remoteCommandType: {
      type: String,
      default: ''
    },
    deviceDataList: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      form: {
      },
      defaultForm: {
        logDateSpan: ''
      },
      formArray: [
        {
          label: "日志时间周期", key: "logDateSpan", col: 24, type: "select",
          options: [
            {label: '1天内', value: 1},
            {label: '2天内', value: 2},
            {label: '3天内', value: 3},
            {label: '4天内', value: 4},
            {label: '5天内', value: 5},
            {label: '6天内', value: 6},
            {label: '7天内', value: 7},
          ],
          rule: {required: true, message: '日志时间周期不能为空！', trigger: 'blur'},
        },
        {
          label: "等待时间", key: "wait", col: 24, type: "number",
          rule: {required: true, message: '等待时间不能为空！', trigger: 'blur'},
        },
      ],
      loading: false,
      // 获取日志轮询倒计时
      getLogDuration: 30,
      getLogTimer: null
    }
  },
  computed: {
    visible: {
      get() {
        return this.value
      },
      set(val) {
        if (!val) {
          this.loading = false;
          this.$refs.uFormRef.reset();
          // 如果关闭前还在轮询获取日志则停止
          if (this.getLogTimer) this.clearGetLogInterval()
        }
        return this.$emit('input', val)
      }
    },
    title() {
      if (this.remoteCommandType) {
        return COMMAND_TYPE_DICT[this.remoteCommandType].title;
      }
      return ''
    }
  },
  methods: {
    // 确定按钮
    onsubmit(callBack) {
      //拉取日志form rule
      if(Object.keys(this.form).length===2){
        if(!this.form.logDateSpan&&!this.form.fileDate){
          this.$modal.msgWarning('驱动中心日志时间周期和android设备指定日期必须选择其中一个');
          callBack()
          return
        }
      }
      const fnName = COMMAND_TYPE_DICT[this.remoteCommandType].fnName;
      if (!fnName) return;
      this[fnName](callBack)
    },
    // 重启
    async restart(callBack) {
      try {
        this.loading = true;
        const params = this.deviceDataList.map(item => {
          return {
            ipAddress: item.ipAddress,
            deviceId: item.deviceId,
            wait: this.form.wait
          }
        })
        const res = await reqRemoteRestart(params);
        this.visible = false;
        this.$modal.msgSuccess('指令下发成功！');

      } catch (err) {
        console.log("reqRemoteRestart 接口数据异常", err)
      } finally {
        this.loading = false;
        callBack && callBack()
      }
    },
    // 设备自检
    async selfCheck(callBack) {
      try {
        this.loading = true;
        const params = this.deviceDataList.map(item => {
          return {
            ipAddress: item.ipAddress,
            deviceId: item.deviceId,
            wait: this.form.wait
          }
        })
        const res = await reqRemoteSelfCheck(params);
        this.visible = false;
        this.$modal.msgSuccess('指令下发成功！');
      } catch (err) {
        console.log("reqRemoteSelfCheck 接口数据异常", err)
      } finally {
        this.loading = false;
        callBack && callBack()
      }
    },
    // 关机
    async shutdown(callBack) {
      try {
        this.loading = true;
        const params = this.deviceDataList.map(item => {
          return {
            ipAddress: item.ipAddress,
            deviceId: item.deviceId,
            wait: this.form.wait
          }
        })
        const res = await reqRemoteShutdown(params);
        this.visible = false;
        this.$modal.msgSuccess('指令下发成功！');
      } catch (err) {
        console.log("reqRemoteShutdown 接口数据异常", err)
      } finally {
        this.loading = false;
        callBack && callBack()
      }
    },

    // @descriptions 获取拉取日志流水号
    async getLogFileMessageCode(callBack) {
      // if (!this.deviceDataList[0].ipAddress) {
      //   this.$modal.msgWarning('该设备暂无设置IP地址，无法拉取日志！');
      //   return callBack && callBack()
      // }
      try {
        this.loading = true;
        const res = await reqGetLogMessageCode({
          ipAddress: this.deviceDataList[0].ipAddress,
          deviceId: this.deviceDataList[0].deviceId,
          logDateSpan: this.form.logDateSpan,
          fileDate:this.form.fileDate
        })
        if (res.data) {
          // 30秒轮询获取截图
          if (this.getLogTimer) return
          // 设置倒计时30秒
          this.getLogDuration = 30
          this.getLogTimer = setInterval(() => {
            // 倒计时30秒轮询结束
            if (this.getLogDuration <= 0) {
               this.$modal.msgWarning("拉取日志超时！")
               callBack && callBack()
              return this.clearGetLogInterval()
            }
            this.getLogDuration -= 3
            console.log('轮询获取日志倒计时', this.getLogDuration)
            this.downloadLogFile(res.data, callBack)
          }, 3000)
        } else {
          this.loading = false;
          this.$modal.msgWarning("获取拉取日志流水号messageCode失败！")
        }
      } catch (err) {
        this.loading = false;
        console.log("reqGetScreenshot 接口数据异常", err)
      }
    },

    // 清除获取截图轮询定时器
    clearGetLogInterval() {
      clearInterval(this.getLogTimer)
      this.getLogTimer = null
      this.loading = false;
    },

    // 拉取日志
    async downloadLogFile(messageCode, callBack) {
      const date = this.$moment().format('YYYY-MM-DD k-mm-ss');
      reqGetLogFile({
        messageCode,
        dateSpan: this.form.logDateSpan,
        fileDate:this.form.fileDate
      }).then(res => {
        console.log(res, '收到的文件')
        if (res.size === 0) { // 返回的json，中间件还未上传到数据库

        } else { // 返回的数据流，中间件已上传到数据库
          this.visible = false;
          callBack && callBack()
          this.clearGetLogInterval()
          saveAs(new Blob([res], {type: "application/zip"}), `设备日志_${date}.zip`)
        }
      })
    },

    // 根据不同指令设置表单选项和表单值
    setFormAndFormArray(type) {
      if (type === 'pullLog') {
        this.defaultForm = {logDateSpan: '',fileDate:''};
        this.formArray = [
          {
            label: "驱动中心日志时间周期", key: "logDateSpan", col: 24, type: "select",disabled:false,
            options: [
              {label: '1天内', value: 1},
              {label: '2天内', value: 2},
              {label: '3天内', value: 3},
              {label: '4天内', value: 4},
              {label: '5天内', value: 5},
              {label: '6天内', value: 6},
              {label: '7天内', value: 7},
            ],
            // rule: {required: true, message: '日志时间周期不能为空！', trigger: 'blur'},
          },
          {
            label:"android设备指定日期",key:'fileDate',col:24,type:'date',disabled:false
          }
        ];
      } else {
        this.defaultForm = {wait: 60};
        this.formArray = [
          {
            label: "等待时间(秒)", key: "wait", col: 24, type: "number",
            rule: {required: true, message: '等待时间不能为空！', trigger: 'blur'},
          },
        ];
      }
      this.form = JSON.parse(JSON.stringify(this.defaultForm));
    }
  },
  watch: {
    remoteCommandType: {
      immediate: true,
      handler(newValue) {
        if (newValue) {
          // 根据不同指令设置表单选项和表单值
          this.setFormAndFormArray(newValue)
        }
      }
    },
    form:{
      deep:true,
      //指令类型 pullLog 选择框互斥控制
      handler(newValue){
        if(Object.keys(newValue).length===2){
          if(newValue.logDateSpan){
            this.formArray[1].disabled=true
          }else{
            this.formArray[1].disabled=false
          }
          if(newValue.fileDate){
            this.formArray[0].disabled=true
          }else{
            this.formArray[0].disabled=false
          }
        }
      }
    }
  },
}
</script>

<style lang="scss" scoped>

</style>
